{% extends "base.html" %}
{% load staticfiles %}
{% block title %}购物车{% endblock %}
{% block css %}
    <link rel="stylesheet" href="{% static 'css/carts.css' %}">
    <link rel="stylesheet" href="{% static 'css/index.css' %}">
    <link rel="stylesheet" href="{% static 'css/select2.min.css' %}">
    <style rel="stylesheet">
        .disable-pointer-events{ pointer-events: none;}
    </style>
{% endblock %}

{% block cart %}active{% endblock %}

{% block content %}
    <section class="cartMain">
        <div class="cartMain_hd">
            <ul class="order_lists cartTop">
                <li class="list_chk">
                    <!--所有商品全选-->
                    <input type="checkbox" id="all" class="whole_check "
                           style="display: inline-block;position:relative;left: -8px;top: 4px">
                    全选
                </li>
                <li class="list_con">商品信息</li>
                <li class="list_info">商品参数</li>
                <li class="list_price">单价</li>
                <li class="list_amount">数量</li>
                <li class="list_sum">金额</li>
                <li class="list_op">操作</li>
            </ul>
        </div>

        <div class="cartBox">
            <div class="order_content">
                {% for good in goods %}

                     <ul style="position: relative" class="order_lists" goodsid="{{good.id}}">
                        <li class="list_chk">
                            <input type="checkbox" id="checkbox_2" class="son_check " style="display: inline-block;position:absolute;left: 30px;top: 30px">
                        </li>
                        <li class="list_con">
                            <div class="list_text">{{good.good__name}}</div>
                        </li>
                        <li class="list_info">
                            <p>规格：{{ good.good__specification }}</p>
                            <p>单位：{{ good.good__unit }}</p>
                        </li>
                        <li class="list_price">
                            <p class="price">￥{{ good.good__selling_price | floatformat:2}}</p>
                        </li>
                        <li class="list_amount">
                            <div class="amount_box">
                                <a href="javascript:;" class="reduce" goodsid="{{ good.id }}" cartgoodid="{{ good.good__id }}">-</a>
                                <input type="text" value="{{ good.amount }}" class="sum" readonly="">
                                <a href="javascript:;" class="plus" goodsid="{{ good.id }}" cartgoodid="{{ good.good__id }}">+</a>
                            </div>
                        </li>
                        <li class="list_sum">
{#                            有空格会影响字符串的计算, 精度不够也会影响#}
                            <p class="sum_price">￥{{ good.sum_price | floatformat:2 }}</p>
                        </li>
                        <li class="list_op">
                            <p class="del"><a href="javascript:;" class="delBtn" goodsid="{{ good.id }}">移除商品</a></p>
                        </li>
                    </ul>

                {% endfor %}
            </div>
        </div>
        <!--底部-->
        <div class="bar-wrapper d-flex justify-content-between">
            <div class="select d-flex align-items-center justify-content-around">
                <label for="people" class="flex-fill h5" style="width: 90px; border: none;">单位:</label>
                <select class="js-example-basic-single" id="people">

                    {% for organization in organizations %}
                        <option class=""
                                value="{{ organization.id }}">
                            {{ organization.organization }}
                        </option>
                    {% endfor %}

                </select>
            </div>
            <div class="bar-right">
                <div class="piece">已选商品<strong class="piece_num" id="all_count">0</strong>件</div>
                <div class="totalMoney">共计: <strong class="total_text" id="all_price">0.00</strong></div>
                <div class="calBtn"><a href="javascript:;" id="jiesuan">结算</a></div>
            </div>
        </div>
    </section>
    <section class="model_bg" style="display: none;"></section>
    <section class="my_model" style="display: none;">
        <p class="title">删除商品<span class="closeModel">X</span></p>
        <p>您确认要删除吗？</p>
        <div class="opBtn">
            <a href="javascript:;" class="dialog-sure">确定</a>
            <a href="javascript:;" class="dialog-close">关闭</a>
        </div>
    </section>
{% endblock %}
{% block js %}
    <script src="{% static 'js/jquery.min.js' %}"></script>
{#    处理全选跟单选的问题，结账的总价，删除商品#}
    <script src="{% static 'js/carts.js' %}"></script>
    <script src="{% static 'js/select2.min.js' %}"></script>

    <script>
        function totalMoney() {
            var total_money = 0;
            var total_count = 0;
            var calBtn = $('.calBtn a');
            // 将金额转化为字符串拼接转成整数，求和之后再除100
            $sonCheckBox = $('.son_check');
            $sonCheckBox.each(function () {
                if ($(this).is(':checked')) {
                    var goods = $(this).parents('.order_lists').find('.sum_price').html().substring(1);
                    var num = parseInt($(this).parents('.order_lists').find('.sum').val());
                    var int_float = goods.split('.');
                    goods = int_float[0] + int_float[1];
                    total_money += Number(goods);
                    total_count += num;
                }
            });
            $('.total_text').html('￥' + total_money / 100);
            $('.piece_num').html(total_count);

            // console.log(total_money,total_count);

            if (total_money != 0 && total_count != 0 && document.getElementById("people").value != "") {
                if (!calBtn.hasClass('btn_sty')) {
                    calBtn.addClass('btn_sty');
                }
            } else {
                if (calBtn.hasClass('btn_sty')) {
                    calBtn.removeClass('btn_sty');
                }
            }
        }
        $('.plus').click(function (event) {
            {#添加#}
            <!--将数据同步到服务器-->
            // 禁用按钮
            var add_a = $(this);
            add_a.addClass("disable-pointer-events");

            var csrfmiddlewaretoken = $('input[name="csrfmiddlewaretoken"]').val();

            var goods_id = $(this).attr('goodsid');
            var cart_goods_id = $(this).attr('cartgoodid');

            var amount = add_a.parent().find(".sum");
            var sum_price = add_a.parent().parent().parent().find(".sum_price");
            var price = add_a.parent().parent().parent().find(".price").html().substring(1);

            var data = {
                goods_id: goods_id,
                cart_goods_id: cart_goods_id,
                csrfmiddlewaretoken: csrfmiddlewaretoken,
            };
            $.ajax({
                async: false,
                url: '{% url "cart:good_add" %}',
                data: data,
                type: 'post',
                success: function (data) {
                    if (data === "1") {
                        // 启用按钮
                        // 减号
                        var reduce_a =add_a.parents().find('.reduce');
                        if (reduce_a.hasClass('disable-pointer-events')) reduce_a.removeClass('disable-pointer-events');

                        add_a.removeClass('disable-pointer-events');
                        amount[0].value = Number(amount[0].value)+1;
                        var tmp_sum_price = (Number(sum_price.html().substring(1).split('.').join(''))
                                +
                                Number(price.split('.').join(''))).toString();
                        // 更新当前价格
                        sum_price.html("￥"+ tmp_sum_price.slice(0,-2) + '.' + tmp_sum_price.slice(-2));
                        // 计算总额
                        totalMoney();
                    }
                },
                error: function () {
                    <!--按钮设置了两个点击事件-->

                    event.stopImmediatePropagation()
                }

            })
        });

        $('.reduce').click(function (event) {
            {#减少 #}
            <!--将数据同步到服务器-->
            var reduce_a = $(this);
            reduce_a.addClass("disable-pointer-events");

            if ($(this).next('input').val() <= 1) {
                event.stopImmediatePropagation();
                return;
            }

            var amount = reduce_a.parent().find(".sum");
            var sum_price = reduce_a.parent().parent().parent().find(".sum_price");
            var price = reduce_a.parent().parent().parent().find(".price").html().substring(1);

            var csrfmiddlewaretoken = $('input[name="csrfmiddlewaretoken"]').val();
            var goodsid = $(this).attr('goodsid');
            var cart_goods_id = $(this).attr('cartgoodid');

            var data = {
                goods_id: goodsid,
                cart_goods_id: cart_goods_id,
                csrfmiddlewaretoken: csrfmiddlewaretoken,
            };

            $.ajax({
                async: false,
                url: '{% url "cart:good_reduce" %}',
                type: 'post',
                data: data,
                success: function (data) {
                    if (data === "1") {
                        // 启用按钮
                        var plass_a =reduce_a.parent().find(".plus");
                        if (plass_a.hasClass('disable-pointer-events')) plass_a.removeClass('disable-pointer-events');

                        reduce_a.removeClass('disable-pointer-events');
                        amount[0].value = Number(amount[0].value)-1;
                        var tmp_sum_price = (Number(sum_price.html().substring(1).split('.').join(''))
                                -
                                Number(price.split('.').join(''))).toString();
                        // 更新当前价格
                        sum_price.html("￥"+ tmp_sum_price.slice(0,-2) + '.' + tmp_sum_price.slice(-2));
                        // 计算总额
                        totalMoney();
                    }
                },
                error: function () {
                    <!--按钮设置了两个点击事件-->

                    event.stopImmediatePropagation()
                }

            })
        });

        $('.delBtn').click(function () {
            var goodsid = $(this).attr('goodsid');
            $('.dialog-sure').attr('goodsid', goodsid);
        });

        $('.dialog-sure').click(function (event) {
            {#确认删除#}
            var goodsid = $(this).attr('goodsid');
            var csrfmiddlewaretoken = $('input[name="csrfmiddlewaretoken"]').val();

            var data = {
                goods_id: goodsid,
                csrfmiddlewaretoken: csrfmiddlewaretoken,
            };

            $.ajax({
                type: 'post',
                url: '{% url "cart:good_remove" %}',
                data: data,
                async: false,
                success: function (result) {

                },
                error: function (event) {
                    //停止事件传播
                    event.stopImmediatePropagation()
                }

            })
        });

        //单击结算按钮
        $('#jiesuan').click(function () {
            var hand_people = document.getElementById("people").value;
            cks = $('.son_check');
            var drop_item = [];
            $.each(cks, function (index, ck) {
                if (!$(ck).prop('checked')) {
                    var goodsid = $(ck).parents('.order_lists').attr('goodsid');
                    drop_item.push({'goodsid': goodsid})
                }
            });

            if (drop_item.length === cks.length || document.getElementById("people").value === "") {
                return;
            }

            var url = "{% url 'cart:jiesuan' %}"+'?drop_item=' + JSON.stringify(drop_item) +'&hand_people=' + hand_people;

            $(".order_content")[0].innerHTML="";
            totalMoney();
            window.open(url);
            {#$(this).attr('href', url);#}
            {#$(this).attr("target","_blank");#}
        })

    </script>
    <script>
        // 选择搜索框
        $(document).ready(function () {
            $('#people').select2();
        });
    </script>
{% endblock %}